/**
 * 用户信息同步工具模块
 * 处理用户信息的获取、同步和更新
 */

class UserSync {
  constructor() {
    this.cloudReady = false
    this.initCloud()
  }

  /**
   * 初始化云开发
   */
  initCloud() {
    if (wx.cloud) {
      this.cloudReady = true
    } else {
      console.warn('云开发未初始化')
    }
  }

  /**
   * 同步用户信息（适用于新设备登录）
   */
  async syncUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      
      if (!isLoggedIn || !userInfo || !userInfo._openid) {
        return {
          success: false,
          message: '用户未登录',
          data: null
        }
      }

      // 从云端获取最新用户信息
      const cloudUserInfo = await this.getUserInfoFromCloud()
      
      if (cloudUserInfo.success) {
        // 更新本地存储
        wx.setStorageSync('userInfo', cloudUserInfo.data)
        
        return {
          success: true,
          message: '用户信息同步成功',
          data: cloudUserInfo.data
        }
      } else {
        // 云端获取失败，返回本地数据
        return {
          success: false,
          message: cloudUserInfo.message || '获取用户信息失败',
          data: userInfo
        }
      }
    } catch (error) {
      console.error('同步用户信息失败:', error)
      return {
        success: false,
        message: error.message || '同步失败',
        data: null
      }
    }
  }

  /**
   * 从云端获取用户信息
   */
  async getUserInfoFromCloud() {
    return new Promise((resolve, reject) => {
      if (!this.cloudReady) {
        reject(new Error('云开发未初始化'))
        return
      }

      wx.cloud.callFunction({
        name: 'getUserInfo',
        data: {},
        success: res => {
          if (res.result && res.result.success) {
            resolve({
              success: true,
              data: res.result.data,
              message: res.result.message || '获取成功'
            })
          } else {
            resolve({
              success: false,
              data: null,
              message: res.result?.message || '获取用户信息失败'
            })
          }
        },
        fail: error => {
          reject(error)
        }
      })
    })
  }

  /**
   * 同步用户微信头像和昵称
   */
  async syncUserProfile(avatarUrl, nickName) {
    return new Promise((resolve, reject) => {
      if (!this.cloudReady) {
        reject(new Error('云开发未初始化'))
        return
      }

      wx.cloud.callFunction({
        name: 'syncUserProfile',
        data: {
          avatarUrl: avatarUrl,
          nickName: nickName
        },
        success: res => {
          if (res.result && res.result.success) {
            // 更新本地存储
            wx.setStorageSync('userInfo', res.result.data)
            
            resolve({
              success: true,
              data: res.result.data,
              message: res.result.message || '同步成功'
            })
          } else {
            resolve({
              success: false,
              data: null,
              message: res.result?.message || '同步失败'
            })
          }
        },
        fail: error => {
          reject(error)
        }
      })
    })
  }

  /**
  /**
   * 检查用户登录状态（包含云端验证）
   */
  async checkLoginStatus() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      
      if (!isLoggedIn || !userInfo || !userInfo._openid || !userInfo._id) {
        return {
          isLoggedIn: false,
          userInfo: null,
          message: '用户未登录'
        }
      }

      // 尝试从云端验证用户状态
      const cloudUserInfo = await this.getUserInfoFromCloud()
      
      if (cloudUserInfo.success) {
        return {
          isLoggedIn: true,
          userInfo: cloudUserInfo.data,
          message: '用户已登录'
        }
      } else {
        // 云端验证失败，清除本地数据
        this.clearLocalData()
        return {
          isLoggedIn: false,
          userInfo: null,
          message: '用户登录状态异常'
        }
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
      return {
        isLoggedIn: false,
        userInfo: null,
        message: error.message || '检查失败'
      }
    }
  }

  /**
   * 清除本地用户数据
   */
  clearLocalData() {
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('isLoggedIn')
  }

  /**
   * 获取格式化的用户信息
   */
  getFormattedUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      return {
        isLoggedIn: false,
        memberLevel: '普通会员',
        balance: '¥0.00',
        points: '0',
        avatarUrl: '/images/icons/userAvatar.png',
        nickName: '游客'
      }
    }

    return {
      isLoggedIn: true,
      memberLevel: userInfo.memberLevelInfo?.name || '普通会员',
      balance: `¥${userInfo.balance?.toFixed(2) || '0.00'}`,
      points: userInfo.totalPoints?.toString() || '0',
      avatarUrl: userInfo.avatarUrl || '/images/icons/userAvatar.png',
      nickName: userInfo.nickName || '微信用户'
    }
  }
}

// 创建单例实例
const userSync = new UserSync()

// 导出实例
module.exports = {
  userSync
}